package com.base.project.deeplinks

import android.app.Activity
import android.content.Intent
import android.net.Uri
import com.blankj.utilcode.util.LogUtils
import com.google.firebase.dynamiclinks.PendingDynamicLinkData
import com.google.firebase.dynamiclinks.ktx.dynamicLinks
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * Created by Orange on 2022/12/4 17:50.
 */
class FirebaseTask : Task {

    override suspend fun asyncGetUrl(activity: Activity, intent: Intent?) =
        suspendCancellableCoroutine { continuation ->
            // https://firebase.google.com/docs/dynamic-links/android/receive?hl=zh-cn
            Firebase.dynamicLinks
                .getDynamicLink(Intent())
                .addOnSuccessListener(activity) { pendingDynamicLinkData: PendingDynamicLinkData? ->
                    // Get deep link from result (may be null if no link is found)
                    var deepLink: Uri?
                    var tag = "firebase";

                    deepLink = pendingDynamicLinkData?.link

                    if (deepLink == null && intent?.dataString?.isNotEmpty() == true) {
                        deepLink = Uri.parse(intent.dataString)
                        tag = "firebase intent dataString"
                    }
                    deepLink?:continuation.resume(null)
                    deepLink?.let {
                        continuation.resume(LinkData(uri = it, tag = tag))
                    }
                }
                .addOnFailureListener(activity) { e ->
                    continuation.resume(null)
                    LogUtils.e(e)
                }
        }

}